const db = require('../utils/db')

// 获取视频相关评论
exports.selectComments = (req, res)=>{
  const sql = `
    select c.id, c.content, c.createAt, c.userId,
      u.username, u.nickname, u.avatarUrl,
      (select count(*) from commentlikes cl where cl.commentId=c.id) as likeCount
    from comments c, users u
    where c.videoId=${req.params.videoId} and c.userId=u.id
    order by c.createAt desc, likeCount desc`
  db.query(sql,(err, results)=>{
    if(err) return res.er(err)
    res.send({code:0, msg:'获取评论成功', comments:results})
  })
}

// 发表评论
exports.addComment = (req, res)=>{
  let sql = `insert into comments set ?`
  const createAt = Date.now() 
  const values = {...req.body, userId: req.user.id, createAt}
  console.log(values);
  db.query(sql, values, (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1) return res.er('发表评论失败1')
    sql = `
      select c.id, c.content, c.createAt,
        u.username, u.nickname, u.avatarUrl,
        (select count(*) from commentlikes cl where cl.commentId=c.id) as likeCount
      from comments c, users u
      where c.id=${results.insertId} and u.id=${req.user.id} and c.userId=${req.user.id}`
    db.query(sql,(err, results2)=>{
      console.log(results2);
      if(err) return res.er(err)
      if(results2.length != 1) return res.er('发表评论失败2')
      res.send({code:0, msg:'发表评论成功', comment:results2[0]})
    })
  })
}

// 点赞评论
exports.addCommentLike = (req, res)=>{
  const sql = `insert into commentlikes set ?`
  const values = {
    commentId: req.params.id,
    userId: req.user.id,
    createAt: Date.now()
  }
  db.query(sql, values, (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1) return res.er('点赞评论失败')
    res.send({code:0, msg:'点赞评论成功'})
  })
}

// 取消点赞评论
exports.deleteCommentLike = (req, res)=>{
  const sql = `delete from commentlikes where commentId=`+req.params.id
  db.query(sql, (err, results)=>{
    // console.log(results);
    if(err) return res.er(err)
    if(results.affectedRows != 1) return res.er('取消点赞评论失败')
    res.send({code:0, msg:'取消点赞评论成功'})
  })
}

// 获取用户点赞的评论
exports.selectCommentLikes = (req, res)=>{
  const sql = `select commentId as id from commentlikes
    where userId=${req.user.id}`
  db.query(sql, (err, results)=>{
    if(err) return res.er(err)
    res.send({code:0, msg:'获取点赞评论成功', dt:{commentlikes:results}})
  })
}
